package com.htfyun.factorytest.common;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.text.TextUtils;

import com.htfyun.factorytest.R;
import com.htfyun.factorytest.utils.DebugLog;
import com.htfyun.factorytest.utils.FileReadWrite;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by sst on 2018/7/7.
 */

public class BatteryInfo {

    private final Context mContext;

    private int batteryTemperature = 0;
    private int batteryLevel = 0;
    private int batteryVoltage = 0;
    private String batteryStatusString = "";
    private int batteryStatus = -1;
    private String batteryChargePlugTypeString = "";
    private int batteryChargePlugType = -1;
    private String batteryHealthString = "";
    private int batteryHealth = -1;
    private String batteryCapacityInfo = "";

    //    private static final String CURRENT_NOW_PATH = "/sys/devices/platform/ff650000.i2c/i2c-0/0-001c/rk818-battery/power_supply/battery/current_now";
    private static final String CURRENT_NOW_PATH = "/sys/devices/platform/ff180000.i2c/i2c-0/0-0020/rk817-battery/power_supply/battery/current_now";
    private static final String BATTERY_INFO_PATH = "/sys/bus/platform/devices/rk817-battery/bat";

    private OnBatteryChangedListener mListener;

    public BatteryInfo(Context ctx) {
        mContext = ctx;
    }

    public void setOnBatteryChangedListener(OnBatteryChangedListener listener) {
        this.mListener = listener;
    }

    public void startMonitor() {
        mContext.registerReceiver(mBatteryReceiver, new IntentFilter(
                Intent.ACTION_BATTERY_CHANGED));
    }

    public void stopMonitor() {
        mContext.unregisterReceiver(mBatteryReceiver);
    }

    public int getBatteryTemperature() {
        return batteryTemperature / 10;
    }

    public int getBatteryLevel() {
        return batteryLevel;
    }

    public int getBatteryVoltage() {
        return batteryVoltage;
    }

    public String getBatteryStatusString() {
        return batteryStatusString;
    }

    public String getBatteryChargePlugTypeString() {
        return batteryChargePlugTypeString;
    }

    public String getBatteryHealthString() {
        return batteryHealthString;
    }

    public int getBatteryStatus() {
        return batteryStatus;
    }

    public int getBatteryChargePlugType() {
        return batteryChargePlugType;
    }

    public int getBatteryHealth() {
        return batteryHealth;
    }

    public int getBatteryCurrent_mAh() {

        int batteryCurrent_mA = -1;
        try {
            String currentStr = FileReadWrite.readFileByLines(CURRENT_NOW_PATH);
            int current = Integer.decode(currentStr);
            batteryCurrent_mA = current / 1000;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return batteryCurrent_mA;

    }

    public int getRatedBatteryCapacity_mAh() {
        ArrayList<Integer> result = new ArrayList<>();
        try {
            String batteryInfo = FileReadWrite.readFileByLines(BATTERY_INFO_PATH);
            String reg = "(?<=fcc=)\\d{4}";

            Pattern pattern = Pattern.compile(reg);
            Matcher matcher = pattern.matcher(batteryInfo);
            while (matcher.find()) {
                String cap = matcher.group();
                result.add(Integer.parseInt(cap));
                DebugLog.e("cap = " + cap);
            }
            if (result.isEmpty()) {
                return 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.get(0);
    }

    /**
     * 电池温度是否为有效值
     */
    public static boolean isBatteryTemperatureInValidRange(int temp) {
        return Constants.MIN_TEMPERATURE_BATTERY <= temp && temp <= Constants.MAX_TEMPERATURE_BATTERY;
    }

    /**
     * 主板温度是否为有效值
     */
    public static boolean isMotherboardTemperatureInValidRange(int temp) {
        return Constants.MIN_TEMPERATURE_MOTHERBOARD <= temp && temp <= Constants.MAX_TEMPERATURE_MOTHERBOARD;
    }

    /**
     * 获取主板温度
     */
    public static int getMotherboardTemperature() {
        int temp = Constants.INVALID_TEMPERATURE;
        String temperatureInfo = FileReadWrite.readFileByLines(Constants.TEMPERATURE_PATH).trim();
        DebugLog.d("temperatureInfo = " + temperatureInfo);
        if (!TextUtils.isEmpty(temperatureInfo)) {
            if (temperatureInfo.contains(":")) {
                temp = Integer.parseInt(temperatureInfo.substring(0, temperatureInfo.length() - 1));
            } else {
                temp = Integer.parseInt(temperatureInfo);
            }
        }
        return temp;
    }

    public int getBatteryCapacity_mAh() {

        ArrayList<Integer> result = new ArrayList<>();
        try {
            String batteryInfo = FileReadWrite.readFileByLines(BATTERY_INFO_PATH);
            String reg = "(?<=remain_cap=)\\d+";

            Pattern pattern = Pattern.compile(reg);
            Matcher matcher = pattern.matcher(batteryInfo);
            while (matcher.find()) {
                String cap = matcher.group();
                result.add(Integer.parseInt(cap));
//                DebugLog.e("cap = " + cap);
            }
            if (result.isEmpty()) {
                return 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.get(0) / 1000;

    }

    private BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            batteryVoltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);

            batteryTemperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);

            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);
            batteryLevel = (int) (((float) level / scale) * 100);

            int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN);
            batteryStatus = status;
            int statusResId = R.string.battery_status_unknown;
            switch (status) {
                case BatteryManager.BATTERY_STATUS_CHARGING:
                    statusResId = R.string.battery_status_charging;
                    break;
                case BatteryManager.BATTERY_STATUS_DISCHARGING:
                    statusResId = R.string.battery_status_discharging;
                    break;
                case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
                    statusResId = R.string.battery_status_not_charging;
                    break;
                case BatteryManager.BATTERY_STATUS_FULL:
                    statusResId = R.string.battery_status_full;
                    break;
            }
            batteryStatusString = mContext.getResources().getString(statusResId);

            // 怎么充
            int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
            batteryChargePlugType = chargePlug;
            int chargePlugResId = R.string.battery_plugged_unknown;
            switch (chargePlug) {
                case BatteryManager.BATTERY_PLUGGED_AC:
                    chargePlugResId = R.string.battery_plugged_ac;
                    break;
                case BatteryManager.BATTERY_PLUGGED_USB:
                    chargePlugResId = R.string.battery_plugged_usb;
                    break;
                case BatteryManager.BATTERY_PLUGGED_WIRELESS:
                    chargePlugResId = R.string.battery_plugged_wireless;
                    break;
            }
            batteryChargePlugTypeString = mContext.getResources().getString(chargePlugResId);


            int health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, BatteryManager.BATTERY_HEALTH_UNKNOWN);
            batteryHealth = health;
            int healthResId = R.string.battery_health_unknown;
            switch (health) {
                case BatteryManager.BATTERY_HEALTH_GOOD:
                    healthResId = R.string.battery_health_good;
                    break;
                case BatteryManager.BATTERY_HEALTH_OVERHEAT:
                    healthResId = R.string.battery_health_overheat;
                    break;
                case BatteryManager.BATTERY_HEALTH_DEAD: // 未充电时就会显示此状态，这是什么鬼？
                    healthResId = R.string.battery_health_dead;
                    break;
                case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
                    healthResId = R.string.battery_health_over_voltage;
                    break;
                case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
                    healthResId = R.string.battery_health_unknown;
                    break;
                case BatteryManager.BATTERY_HEALTH_COLD:
                    healthResId = R.string.battery_health_cold;
                    break;
            }
            batteryHealthString = mContext.getString(healthResId);

            if (mListener != null) {
                mListener.onBatteryChangedListener(BatteryInfo.this);
            }
        }
    };

    public interface OnBatteryChangedListener {
        void onBatteryChangedListener(BatteryInfo info);
    }


}
